package com.javatest.chapter3;

import org.springframework.util.StopWatch;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author liuziyang
 * @create 2020-04-13 22:51
 */
public class AsyncFutureExample {
    public static String doingSomethingA() {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("----doing something A----");
        return "Task A Result";
    }

    public static String doingSomethingB() {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("----doing something B----");
        return "Task B Result";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 使用Spring的stopwatch
        StopWatch sw = new StopWatch("timer");
        sw.start();

        //1.创建future任务
        FutureTask<String> futureTask = new FutureTask<>(() -> {
            String result = null;
            try {
                result = doingSomethingA();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        });

        // 2.开启异步单元执行任务A
        Thread thread = new Thread(futureTask, "threadA");
        thread.start();

        // 3.执行任务B
        String taskResult = doingSomethingB();

        // 4.同步等待线程A运行结束
        String taskAResult = futureTask.get();

        // 5.打印两个任务运行结果
        System.out.println("task a result " + taskAResult);
        sw.stop();
        System.out.println(sw.prettyPrint());
        System.out.println(sw.shortSummary());
    }
}
